package com.trw.trp.dao;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.trw.trp.bean.ModelBean;
import com.trw.trp.bean.ModelDetail;

public class ModelDaoProxy extends ModelDao {

	private static Map<Long, ModelBean> modelMap = new Hashtable<Long, ModelBean>();
	private static Map<String, Long> modelMap2 = new Hashtable<String, Long>();
	private static Map<Long, ModelDetail> modelDetailMap = new Hashtable<Long, ModelDetail>();
	private static Map<Integer, List<Long>> statusModelMap = new Hashtable<Integer, List<Long>>();

	@Override
	public List<ModelBean> getModels(int status) {
		List<ModelBean> modelList = new ArrayList<ModelBean>();
		if (statusModelMap.get(status) == null) {
			synchronized (modelMap) {
				if (statusModelMap.get(status) == null) {
					List<Long> modelIdList = new ArrayList<Long>();
					List<ModelBean> models = super.getModels(status);
					for (ModelBean model : models) {
						modelMap.put(model.getModelId(), model);
						modelMap2.put(model.getModelName(), model.getModelId());
						modelIdList.add(model.getModelId());
						if (model.getSubModelList() != null
								&& !model.getSubModelList().isEmpty()) {
							for (ModelBean subModel : model.getSubModelList()) {
								modelMap.put(subModel.getModelId(), subModel);
								modelMap2.put(subModel.getModelName(),
										subModel.getModelId());
							}
						}
					}
					statusModelMap.put(status, modelIdList);
				}
			}
		}
		for (Long modelId : statusModelMap.get(status)) {
			ModelBean model = modelMap.get(modelId);
			if (model != null) {
				modelList.add(model);
			}
		}
		return modelList;
	}

	@Override
	public ModelBean getModelById(long modelId) {
		if (modelMap.isEmpty()) {
			getModels(1);
			getModels(2);
		}
		ModelBean model = modelMap.get(modelId);
		if (model != null) {
			try {
				model = (ModelBean) model.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
		}
		return model;
	}

	@Override
	public ModelBean getModelByName(String modelName) {
		ModelBean model = null;
		if (modelMap2.isEmpty()) {
			getModels(1);
			getModels(2);
			getModels(3);
		}
		Long modelId = modelMap2.get(modelName);
		if (modelId != null) {
			model = modelMap.get(modelId);
		}
		return model;
	}

	@Override
	public ModelDetail getModelDetail(long modelId) {
		ModelDetail detail = modelDetailMap.get(modelId);
		if (detail == null) {
			detail = super.getModelDetail(modelId);
			if (detail != null) {
				modelDetailMap.put(modelId, detail);
			}
		}
		if (detail != null) {
			try {
				detail = (ModelDetail) detail.clone();
			} catch (CloneNotSupportedException e) {
				e.printStackTrace();
			}
		}
		return detail;
	}
	
	public void removeDetail(long modelId){
		modelDetailMap.remove(modelId);
	}

}
